package com.ylkj.redis;

import cn.hutool.core.util.StrUtil;
import com.hwl.common.CustomSerializable;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import redis.clients.jedis.Jedis;

/**
 * @Author: wengzx
 * @Date: 2024/10/13
 * @Desc:
 */
@RequiredArgsConstructor
@ToString(exclude = "client")
@Getter
public class RedisConfig implements CustomSerializable {
    private final String host;
    private final int port;
    private final String password;
    private final int database;

    private Jedis client;

    public Jedis getClient() {
        if (client == null) {
            synchronized (this) {
                if (client == null) {
                    Jedis temp = getJedis();
                    client = temp;
                }
            }
        }
        if (!client.isConnected()) {
            client = null;
            return getClient();
        }
        return client;
    }

    public Jedis getJedis() {
        Jedis temp = new Jedis(getHost(), getPort(),1000*60*60);
        if (StrUtil.isNotBlank(getPassword())) {
            temp.auth(getPassword());
        }
        if (getDatabase() > 0) {
            temp.select(getDatabase());
        }
        return temp;
    }
}
